package com.goldsign.pay.common.util.rsa;

import com.goldsign.pay.common.util.AppSignManager;

import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;

import java.io.UnsupportedEncodingException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * 
 * @author xiaoxianwen
 *
 */
public class SigNatrueUtil {
	
	/**公开key字符串**/
	public static String PUBLIC_KEY_STR;
	/**公开key**/
	public static RSAPublicKey PUBLIC_KEY;
	/**私key字符串**/
	public static String PRIVATE_KEY_STR;
	/**私key**/
	public static RSAPrivateKey PRIVATE_KEY;
	public static void main(String[] args) {
		
	}
	static{
		try {
			//服务端的公钥，用于签名
			PUBLIC_KEY_STR=RsaEncrypt.loadKeyByClasspath("PublicKey_ser.keystore");
			PUBLIC_KEY = RsaEncrypt.loadPublicKeyByStr(PUBLIC_KEY_STR);
			//客户端的私钥，用于验签
			PRIVATE_KEY_STR=RsaEncrypt.loadKeyByClasspath("PrivateKey.keystore");
			PRIVATE_KEY = RsaEncrypt.loadPrivateKeyByStr(PRIVATE_KEY_STR);
		} catch (Exception e) {
			
		}
		
		
	}
	
	/**
	 * 私key校验签名是否合法
	 * @param plainText
	 * @param signatrue
	 * @param appId
	 * @return
	 */
	@SuppressWarnings("restriction")
	public static boolean authSigtrueByPrivateKey(String plainText,String signatrue,String appId){
		try {
			BASE64Decoder decoder=new BASE64Decoder();
			byte[] temBytes = decoder.decodeBuffer(signatrue);
			byte[] res_=null;
			if(StringUtils.isBlank(appId)){
				res_ = RsaEncrypt.decrypt(PRIVATE_KEY, temBytes);
			}else{
				String privateKey = AppSignManager.getPrivateKey(appId);
				RSAPrivateKey pri =RsaEncrypt.loadPrivateKeyByStr(privateKey);
				res_ = RsaEncrypt.decrypt(pri, temBytes);
			}
			String restra = new String(res_,"UTF-8");
			if(plainText.equals(restra)){
				return true;
			}else{
				return false;
			}
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}
		return false;
	}
	
	/**
	 * 私key校验签名是否合法
	 * @param plainText
	 * @param signatrue
	 * @return
	 */
	public static boolean authSigtrueByPrivateKey(String plainText,String signatrue){
		
		try {
			BASE64Decoder decoder=new BASE64Decoder();
			byte[] temBytes = decoder.decodeBuffer(signatrue);
			
			byte[] res_ = RsaEncrypt.decrypt(PRIVATE_KEY, temBytes);
			
			String restra = new String(res_,"UTF-8");
			if(plainText.equals(restra)){
				return true;
			}else{
				return false;
			}
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}
		return false;
	}

	
	
	/**
	 * 如果传入字符串以'"'双引号开头并结尾，去掉此头尾返回中间；不是，直接返回原始字符串
	 * @param value
	 * @return
	 */
	private static String wipeOffQuotation(String value) {
		if ((value != null) && (value.length() > 0)
				&& (value.indexOf("\"") == 0)
				&& (value.lastIndexOf("\"") == value.length() - 1)) {
			return value.substring(1, value.length() - 1);
		}
		return value;
	}
	
	
}
